package com.longway.common.kit;

import com.baidubce.http.ApiExplorerClient;
import com.baidubce.http.AppSigner;
import com.baidubce.http.HttpMethodName;
import com.baidubce.model.ApiExplorerRequest;
import com.baidubce.model.ApiExplorerResponse;
import com.jfinal.json.FastJson;
import com.jfinal.kit.Ret;
import com.jfinal.upload.UploadFile;
import com.longway.common.constant.Const;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static org.apache.commons.codec.binary.Base64.encodeBase64;

/**
 * 营业执照认证工具类
 */
public class EnterpriseCertificationKit {
    public static final EnterpriseCertificationKit me = new EnterpriseCertificationKit();

    /**
     * 百度企业三要素核验
     *
     * @param map
     * @return
     */
    public Ret checkBaidu(Map<String, String> map) {
        //企业三要素核验
        ApiExplorerRequest checkRequest = new ApiExplorerRequest(HttpMethodName.GET, Const.checkPath);
        checkRequest.setCredentials(Const.baiduAccessKey, Const.baiduSecretKey);

        checkRequest.addHeaderParameter("Content-Type", "application/json;charset=UTF-8");

        checkRequest.addQueryParameter("companyName", map.get("企业名称"));
        checkRequest.addQueryParameter("creditNo", map.get("企业统一社会信用编码"));
        checkRequest.addQueryParameter("legalPerson", map.get("企业法人"));
        ApiExplorerClient client = new ApiExplorerClient(new AppSigner());
        ApiExplorerResponse response = client.sendRequest(checkRequest);
        // 返回结果格式为Json字符串
        System.out.println(response.getResult());

        Map<String, Object> checkMap = FastJson.getJson().parse(response.getResult(), Map.class);
        if (!"成功".equals(checkMap.get("msg"))) {
            return Ret.fail().set("msg", checkMap.get("msg"));
        }
        Map data = FastJson.getJson().parse(checkMap.get("data").toString(), Map.class);
        if ("0".equals(data.get("result").toString())) {
            return Ret.ok();
        }
        return Ret.fail().set("msg", data.get("desc"));
    }

    /**
     * 阿里云识别营业执照
     *
     * @param uf
     * @return
     */
    public String aliyunOld(UploadFile uf) {
        //API产品路径         http://blicence.market.alicloudapi.com/ai_business_license
        String requestUrl = "http://businessid.market.alicloudapi.com/ai_business_license/v1";
        //阿里云APPCODE
        String appcode = "08a50657ec934be899941e7270670b0a";

        CloseableHttpClient httpClient = null;
        try {
            httpClient = HttpClients.createDefault();
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            // 装填参数
            if (true) {
                //启用BASE64编码方式进行识别
                //内容数据类型是BASE64编码
                String imgFile = "图片路径";
                String imgBase64 = "";
                try {
                    File file = uf.getFile();
                    byte[] content = new byte[(int) file.length()];
                    FileInputStream finputstream = new FileInputStream(file);
                    finputstream.read(content);
                    finputstream.close();
                    imgBase64 = new String(encodeBase64(content));
                } catch (IOException e) {
                    e.printStackTrace();
                    return "";
                }
                params.add(new BasicNameValuePair("AI_BUSINESS_LICENSE_IMAGE", imgBase64));
                params.add(new BasicNameValuePair("AI_BUSINESS_LICENSE_IMAGE_TYPE", "0"));
            } else {
                //启用URL方式进行识别
                //内容数据类型是图像文件URL链接"https://icredit-api-market.oss-cn-hangzhou.aliyuncs.com/%E8%89%BE%E7%A7%91%E7%91%9E%E7%89%B9_%E9%80%9A%E7%94%A8%E6%96%87%E5%AD%97%E8%AF%86%E5%88%AB_%E8%90%A5%E4%B8%9A%E6%89%A7%E7%85%A7%E8%AF%86%E5%88%AB/%E8%90%A5%E4%B8%9A%E6%89%A7%E7%85%A7.jpg"
                params.add(new BasicNameValuePair("AI_BUSINESS_LICENSE_IMAGE", uf.getFile().getPath()));
                params.add(new BasicNameValuePair("AI_BUSINESS_LICENSE_IMAGE_TYPE", "1"));
            }

            // 创建一个HttpGet实例
            HttpPost httpPost = new HttpPost(requestUrl);
            httpPost.addHeader("Authorization", "APPCODE " + appcode);
            httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

            // 设置请求参数
            httpPost.setEntity(new UrlEncodedFormEntity(params, "utf-8"));

            // 发送GET请求
            HttpResponse execute = httpClient.execute(httpPost);

            // 获取状态码
            int statusCode = execute.getStatusLine().getStatusCode();
            System.out.println(statusCode);

            // 获取结果
            HttpEntity entity = execute.getEntity();
            String result = EntityUtils.toString(entity, "utf-8");
            System.out.println(result);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return "";
    }

    public String aliyun(UploadFile uf) throws IOException {
        //API产品路径http(s)://businessid.market.alicloudapi.com/ai_business_license/v1
        String requestUrl = "https://businessid.market.alicloudapi.com/ai_business_license/v1";
        //阿里云APPCODE
        String appcode = Const.aliyunAppCode;
        String result = "";
        CloseableHttpClient httpClient = null;
        try {
            httpClient = HttpClients.createDefault();
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            // 装填参数
            if (true) {
                //启用BASE64编码方式进行识别
                //内容数据类型是BASE64编码
                String imgFile = "图片路径";
                String imgBase64 = "";
                try {
                    File file = uf.getFile();
//                    File file = new File(imgFile);
                    byte[] content = new byte[(int) file.length()];
                    FileInputStream finputstream = new FileInputStream(file);
                    finputstream.read(content);
                    finputstream.close();
                    imgBase64 = new String(encodeBase64(content));
                } catch (IOException e) {
                    e.printStackTrace();
                    return result;
                }
                params.add(new BasicNameValuePair("IMAGE", imgBase64));
                params.add(new BasicNameValuePair("IMAGE_TYPE", "0"));
            } else {
                //启用URL方式进行识别
                //内容数据类型是图像文件URL链接
                params.add(new BasicNameValuePair("IMAGE", "https://icredit-api-market.oss-cn-hangzhou.aliyuncs.com/%E8%89%BE%E7%A7%91%E7%91%9E%E7%89%B9_%E9%80%9A%E7%94%A8%E6%96%87%E5%AD%97%E8%AF%86%E5%88%AB_%E8%90%A5%E4%B8%9A%E6%89%A7%E7%85%A7%E8%AF%86%E5%88%AB/%E8%90%A5%E4%B8%9A%E6%89%A7%E7%85%A7.jpg"));
                params.add(new BasicNameValuePair("IMAGE_TYPE", "1"));
            }

            // 创建一个HttpGet实例
            HttpPost httpPost = new HttpPost(requestUrl);
            httpPost.addHeader("Authorization", "APPCODE " + appcode);
            httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

            // 设置请求参数
            httpPost.setEntity(new UrlEncodedFormEntity(params, "utf-8"));

            // 发送GET请求
            HttpResponse execute = httpClient.execute(httpPost);

            // 获取状态码
            int statusCode = execute.getStatusLine().getStatusCode();
            System.out.println(statusCode);

            // 获取结果
            HttpEntity entity = execute.getEntity();
            result = EntityUtils.toString(entity, "utf-8");
            System.out.println(result);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return result;
        } finally {
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 百度识别营业执照
     * @param uf
     * @return
     */
//    public Ret baiduyun(UploadFile uf) throws IOException {
//        ApiExplorerRequest identifyRequest = new ApiExplorerRequest(HttpMethodName.POST, Const.identifyPath);
//        identifyRequest.setCredentials(Const.baiduAccessKey, Const.baiduSecretKey);
//
//        identifyRequest.addHeaderParameter("Content-Type", "application/json;charset=UTF-8");
//
//        // 设置jsonBody参数
//        FileInputStream inputStream = new FileInputStream(uf.getFile());
//        int available = inputStream.available();
//        byte[] bytes = new byte[available];
//        inputStream.read(bytes);
//        Base64.Encoder encoder = Base64.getEncoder();
//        String base64Str = encoder.encodeToString(bytes);
//        System.out.println(base64Str);
//        String jsonBody = "{\n  \"baseFile\" : \"" + base64Str + "\"\n}";
//        identifyRequest.setJsonBody(jsonBody);
//
//        ApiExplorerClient client = new ApiExplorerClient(new AppSigner());
//
//        ApiExplorerResponse identifyResponse = client.sendRequest(identifyRequest);
//        // 返回结果格式为Json字符串
//        String identifyResult = identifyResponse.getResult();
//
//        System.out.println(identifyResult);
//        JSONObject identifyMap = JSONObject.parseObject(identifyResult);
//        List<Map<String, String>> childsList = identifyMap.getJSONObject("data").getJSONArray("childs").getJSONObject(1).getObject("childs", List.class);
//
//        if (!identifyMap.get("status").equals("OK")) {
//            return Ret.fail("msg", "企业认证失败,请稍后再试!").set("code", "500");
//        }
//        LhygAppuserQyzl lhygAppuserQyzl = new LhygAppuserQyzl();
//        String[] attrNames = new String[]{"creditNo", "companyName", "companyTag", "address", "legalPerson", "capital", "establishmentTime", "businessTime", "range"};
//        String[] strings = new String[]{"注册号", "名称", "公司类型", "住所", "法定代表人", "注册资本", "成立日期", "营业期限", "经营范围"};
//        for (Map<String, String> stringStringMap : childsList) {
//            for (int i = 0; i < strings.length; i++) {
//                if (stringStringMap.get("Key").equals(strings[i])) {
//                    lhygAppuserQyzl.set(attrNames[i], stringStringMap.get("Text"));
//                    break;
//                }
//            }
//        }
//        return Ret.fail("msg", "企业认证成功").set("code", "200");
//    }
}
